package  com.baomidou.springwind.controller;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.App;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.MemberApp;
import com.baomidou.springwind.entity.Pwallpaper;
import com.baomidou.springwind.entity.Setting;
import com.baomidou.springwind.entity.Wallpaper;
import com.baomidou.springwind.service.IAppService;
import com.baomidou.springwind.service.IMemberAppService;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.IPwallpaperService;
import com.baomidou.springwind.service.ISettingService;
import com.baomidou.springwind.service.IWallpaperService;

/**
 *  首页
 * @author koumiba
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/index")
public class IndexController extends SuperController {
	@Autowired
	private ISettingService settingService;
	@Autowired
	private IPwallpaperService pwallpaperService;
	@Autowired
	private IWallpaperService wallpaperService;
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IMemberAppService memberAppService;
	@Autowired
	private IAppService appService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/home")
	public String home(Model model) {
		// 获取设置表数据
		Setting set = settingService.selectById(1);
		Member user = new Member(); 
		int memberId = HoorayosHelper.getMemberId(request);
		if(memberId > 0){ 
			user = memberService.selectById(memberId);
		}else{
			//没有登录的情况下，也需要初始化一些参数
			user.setSkin(set.getSkin());
			user.setDockpos(set.getDockpos());
			user.setAppxy(set.getAppxy());
			user.setAppsize(set.getAppsize());
			user.setAppverticalspacing(set.getAppverticalspacing());
			user.setApphorizontalspacing(set.getApphorizontalspacing());
			user.setDesk(set.getDesk());
		}
		model.addAttribute("wallpaper",initWallpaper(user, set));
		model.addAttribute("setting",set);
		model.addAttribute("user",user);
		return "index";
	}
	/**
	 * ajax 入口
	 * @param model
	 * @throws Exception 
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action=Action.Skip)
	@RequestMapping("/ajax")
	public String ajax(String ac) throws Exception{
		//所有操作分两种类型：读和写
		//如 getWallpaper 是读操作，setWallpaper 是写操作
		//当遇到写操作时，则需要通过下面登录验证，未登录用户则中断之后的写操作，并输出错误信息
		String[] actions = new String[]{"setWallpaper","setDockPos","setAppXY","addMyApp","delMyApp","moveMyApp","updateMyApp","addFolder","updateFolder"};
		List actionList = Arrays.asList(actions);
		if(actionList.contains(ac)){
			if(!HoorayosHelper.checkLogin(request)){
				return "ERROR_NOT_LOGGED_IN";
			}
		}
		if (ac.equals("getAvatar"))
			return HoorayosHelper.getAvatar(request, HoorayosHelper.getMemberId(request),null);
		if (ac.equals("getMyApp"))
			return getMyApp();
		if(ac.equals("getMyAppById"))
			return getMyAppById();
		if(ac.equals("addMyApp")){
			Map<String,String> data = new HashMap<String,String>();
			data.put("type", "");
			data.put("id", request.getParameter("id"));
			data.put("desk", request.getParameter("desk"));
			return  addApp(data);
		}
		if(ac.equals("delMyApp")){ //删除桌面图标
			delApp(request.getParameter("id"));
		}
		if(ac.equals("moveMyApp")){ //移动桌面图标
			moveApp();
		}
		if(ac.equals("setWallpaper")){ //更改桌面背景
			setWallpaper();			
		}
		if(ac.equals("getWallpaper")){ //获取桌面背景
			return getWallpaper();
		}
		if(ac.equals("setDockPos")){ //更新引用码头
			setDockPos();
		}
		/**
		 * 以下对用户配置进行更新
		 */
		EntityWrapper<Member> ewMember = new EntityWrapper<Member>();
		int mid = HoorayosHelper.getMemberId(request);
		ewMember.and("tbid="+mid);
		Member member = new Member().selectOne(ewMember);
		
		if(ac.equals("setAppXY")){			
			member.setAppxy(request.getParameter("appxy"));
			memberService.insertOrUpdate(member);
		}
		if(ac.equals("setAppSize")){
			member.setAppsize(Integer.parseInt(request.getParameter("appsize")));
			memberService.insertOrUpdate(member);
		}
		if(ac.equals("setAppVerticalSpacing")){
			member.setAppverticalspacing(Integer.parseInt(request.getParameter("appverticalspacing")));
			memberService.insertOrUpdate(member);
		}
		if(ac.equals("setAppHorizontalSpacing")){//更新图标水平间距
			member.setApphorizontalspacing(Integer.parseInt(request.getParameter("apphorizontalspacing")));
			memberService.insertOrUpdate(member);
		}
		if(ac.equals("setDesk")){	//更新默认桌面
			Integer newdesk = Integer.parseInt(request.getParameter("desk"));
			if(newdesk != null && newdesk>=1 && newdesk<=5){
				member.setDesk(newdesk);
				memberService.insertOrUpdate(member);
			}
		}
		return "";
	}

	
	/*************************
	 *    私有方法 
	 *************************/
	/**
	 * 作用描述： 设置桌面参数
	 * @param member
	 *
	 * CopyRight© koumiba
	 * jiangsq123@gmail.com
	 * 2017年3月8日 上午12:01:29
	 */
	 private List<String> initWallpaper(Member user, Setting ts){
		 List<String> wallpaper = new ArrayList<String>();
		 if(user != null && user.getTbid() != null){
			 int state = user.getWallpaperstate();
			 switch (state){
			 case 1:
				 Wallpaper 	wallpaperTemp = wallpaperService.selectById(user.getWallpaperId());
				 wallpaper.add(user.getWallpaperstate().toString());
				 wallpaper.add(wallpaperTemp.getUrl());
				 wallpaper.add(user.getWallpapertype());
				 wallpaper.add(wallpaperTemp.getWidth().toString());
				 wallpaper.add(wallpaperTemp.getHeight().toString());
				 break;
			 case 2:
				 Pwallpaper	 pwallpaperTemp = pwallpaperService.selectById(user.getWallpaperId());
				 wallpaper.add(user.getWallpaperstate().toString());
				 wallpaper.add(pwallpaperTemp.getUrl());
				 wallpaper.add(user.getWallpapertype());
				 wallpaper.add(pwallpaperTemp.getWidth().toString());
				 wallpaper.add(pwallpaperTemp.getHeight().toString());			
				 break;
			 case 3:
				 wallpaper.add(user.getWallpaperstate().toString());
				 wallpaper.add(user.getWallpapertype());
				 break;
			 }
		 }else{
			 Wallpaper 	wallpaperTemp = wallpaperService.selectById(ts.getWallpaperId());
			 wallpaper.add("1");
			 wallpaper.add(wallpaperTemp.getUrl());
			 wallpaper.add(ts.getWallpapertype());
			 wallpaper.add(wallpaperTemp.getWidth().toString());
			 wallpaper.add(wallpaperTemp.getHeight().toString());
		 }
		 return wallpaper;
	 }
	 /**
	  * 获取用户app
	  * koumiba
	  * 2017-2017年3月25日
	 * @throws ClassNotFoundException 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	  */
	 private String getMyApp() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Map desktop = new HashMap(); // 桌面信息表，先初始化，后由struts自动转成json
		EntityWrapper ew = new EntityWrapper();
		
		if (HoorayosHelper.checkLogin(request)) {
			ArrayList<Integer> folderid = new ArrayList<Integer>(); // 文件夹列表
			Member appid = memberService.selectById(HoorayosHelper.getMemberId(request));
			String dock = appid.getDock();
		
			if (dock != null && !dock.equals("")) {
				ew = new EntityWrapper(new MemberApp());
				ew.where("tbid in ("+dock+")");
				ew.orderBy("FIELD(`tbid`, "+dock+")");
				List<MemberApp> tmList = memberAppService.selectList(ew);

				List data = new ArrayList();

				for(int i=0; i<tmList.size(); i++){
					Map<String, Object> tmp = new HashMap<String, Object>();
					MemberApp ma = tmList.get(i);
					if (ma.getType() == "folder") {
						folderid.add(ma.getTbid().intValue());
					}
					tmp.put("type", ma.getType());
					tmp.put("appid", ma.getTbid());
					tmp.put("realappid", ma.getRealid());
					tmp.put("name", ma.getName());

					if (ma.getType() == "file") {
						tmp.put("name", tmp.get("name") + "." + ma.getExt());
					}
					tmp.put("icon", ma.getIcon());
					
					data.add(tmp);					
				}
				desktop.put("dock", data);
			}

			for (int i = 1; i <= 5; i++) {
				Class<?> c = Class
						.forName("com.baomidou.springwind.entity.Member");
				Method m = c.getMethod("getDesk" + i);
				String desk1 = (String) m.invoke(appid);

				if (desk1 != null && desk1 != "") {
					ew = new EntityWrapper(new MemberApp());
					ew.in("tbid", desk1.split(",")).orderBy("FIELD(`tbid`, "+desk1+")");
					
					List<MemberApp> tmaList = memberAppService.selectList(ew);
					List<Object> data = new ArrayList();
					for (int j = 0; j < tmaList.size(); j++) {
						MemberApp tma = tmaList.get(j);
						Map<String, Object> tmp = new HashMap<String, Object>();
						if (tma.getType() == "folder") {
							folderid.add(tma.getTbid().intValue());
						}
						tmp.put("type", tma.getType());
						tmp.put("appid", tma.getTbid());
						tmp.put("realappid", tma.getRealid());
						tmp.put("name", tma.getName());

						if (tma.getType() == "file") {
							tmp.put("name",
									tmp.get("name") + "." + tma.getExt());
						}
						tmp.put("icon", tma.getIcon());
						data.add(tmp);
					}
					desktop.put("desk" + i, data);
				}
			}

			if (!folderid.isEmpty()) {
				List<Object> data = new ArrayList();
				for (Iterator it = folderid.iterator(); it.hasNext();) {
					int tbid = (Integer) it.next();
					Map<String, Object> tmp = new HashMap<String, Object>();
					tmp.put("appid", tbid);
					tmp.put("apps", new ArrayList());
					ew = new EntityWrapper<MemberApp>(new MemberApp());
					ew.where("folder_id="+tbid+" AND member_id="+HoorayosHelper.getMemberId(request)); 
					List<MemberApp> folderapps = new MemberApp().selectList(ew);
					for (int i = 0; i < folderapps.size(); i++) {
						Map<String, Object> tmpp = new HashMap<String, Object>();
						MemberApp vv = folderapps.get(i);
						tmpp.put("type", vv.getType());
						tmpp.put("appid", vv.getTbid());
						tmpp.put("realappid", vv.getRealid());
						tmpp.put("name", vv.getName());
						if (vv.getType() == "file") {
							tmpp.put("name",
									tmpp.get("name") + "." + vv.getExt());
						}
						tmpp.put("icon", vv.getIcon());
						ArrayList al = (ArrayList) tmp.get("apps");
						tmp.put("apps", al.add(tmpp));
					}
					data.add(tmp);
				}
				desktop.put("folder", data);
			}
		} else {
			Setting tbSetting = settingService.selectById(1);

			if (tbSetting.getDock() != null && tbSetting.getDock() != "") {
				List<App> ta = appService.selectByTbid(tbSetting.getDock());
				List data = new ArrayList();
				for (int i = 0; i < ta.size(); i++) {
					Map<String, Object> tmp = new HashMap<String, Object>();
					App v = ta.get(i);
					tmp.put("type", v.getType());
					tmp.put("appid", v.getTbid());
					tmp.put("realappid", v.getTbid());
					tmp.put("name", v.getName());
					tmp.put("icon", v.getIcon());
					data.add(tmp);
				}
				desktop.put("dock", data);
			}
			for (int i = 1; i <= 5; i++) {
				Class<?> c = Class
						.forName("com.baomidou.springwind.entity.Setting");
				Method m = c.getMethod("getDesk" + i);
				String desk1 = (String) m.invoke(tbSetting);

				if (desk1 != null && desk1 != "") {
					ew = new EntityWrapper<App>(new App());
					ew.in("tbid", desk1.split(",")).orderBy("FIELD(`tbid`, "+desk1+")");
					List<App> ta = appService.selectList(ew);
					List data = new ArrayList();
					for (int j = 0; j < ta.size(); j++) {
						Map<String, Object> tmp = new HashMap<String, Object>();
						App v = ta.get(j);
						tmp.put("type", v.getType());
						tmp.put("appid", v.getTbid());
						tmp.put("realappid", v.getTbid());
						tmp.put("name", v.getName());
						tmp.put("icon", v.getIcon());
						data.add(tmp);
					}
					desktop.put("desk" + i, data);
				}
			}
		}
		return JSONObject.toJSONString(desktop);
	}
	 
	 /**
	  * 根据appid获取用户添加的app
	  * @return String
	  * koumiba
	  * 2017年3月27日
	  */
	 private String getMyAppById() {
		 String type = request.getParameter("type");
		 String id = request.getParameter("id");
		 Map<String, Object> app = new HashMap<String, Object>();
		 EntityWrapper ew = new EntityWrapper();
		 if(HoorayosHelper.checkLogin(request)){
			 int mid = HoorayosHelper.getMemberId(request);
			 if("window".equals(type) || "widget".equals(type)){				 
				 ew = new EntityWrapper(new MemberApp());
				 ew.where("tbid="+id+" AND member_id="+mid);
				 MemberApp rs = new MemberApp().selectOne(ew);
				 if(rs != null && rs.getTbid()!=null){
					 ew = new EntityWrapper(new App());
					 ew.and("tbid="+rs.getRealid());
					 if(new App().selectCount(ew)>0){
						app.put("type", rs.getType());
						app.put("appid", rs.getTbid().intValue());
						app.put("realappid", rs.getRealid().intValue());
						app.put("name", rs.getName());
						app.put("icon", rs.getIcon());
						app.put("width", rs.getWidth());
						app.put("height", rs.getHeight());
						app.put("url", new App().selectOne(ew).getUrl());
						if(rs.getType() == "window"){
							app.put("isresize", rs.getIsresize());
							app.put("isopenmax", rs.getIsopenmax());
							app.put("issetbar", rs.getIssetbar());
							app.put("isflash", rs.getIsflash());
						}
					 }else{
						 app.put("error", "ERROR_NOT_FOUND");
					 }
					 
				 }else{
					 app.put("error", "ERROR_NOT_INSTALLED");
				 }						
			 }else if("pwindow".equals(type) || "pwidget".equals(type) || "folder".equals(type) || "file".equals(type) ){
				 ew = new EntityWrapper(new MemberApp());
				 ew.where("tbid="+id+" AND member_id="+mid);
				 MemberApp rs = new MemberApp().selectOne(ew);
				 if(rs != null && rs.getTbid()!=null){
					app.put("type", rs.getType());
					app.put("appid", rs.getTbid().intValue());
					app.put("realappid", rs.getRealid().intValue());
					app.put("name", rs.getName());
					app.put("icon", rs.getIcon());
					app.put("width", rs.getWidth());
					app.put("height", rs.getHeight());
					app.put("url", new App().selectOne(ew).getUrl());
					if(rs.getType().equals("pwindow")){
						app.put("isresize", rs.getIsresize());
						app.put("isopenmax", rs.getIsopenmax());
						app.put("issetbar", rs.getIssetbar());
						app.put("isflash", rs.getIsflash());
					}else if(rs.getType() == "file"){
						app.put("ext", rs.getExt());
						app.put("url", "");
					}
				 }else{
					 app.put("error", "ERROR_NOT_FOUND");
				 }
			 }
		}else{
			ew = new EntityWrapper(new Setting());
			Setting set = new Setting().selectOne(ew);
			String temp = set.getDock()+","+set.getDesk1()+","+set.getDesk2()+","+set.getDesk3()+","+set.getDesk4()+","+set.getDesk5();
			List appids = Arrays.asList(temp.split(","));
			
			if(appids.contains(request.getParameter("id"))){
				App rs = new App().selectById(request.getParameter("id"));
				app.put("type", rs.getType());
				app.put("appid", rs.getTbid());
				app.put("realappid", rs.getTbid());
				app.put("name", rs.getName());
				app.put("icon", rs.getIcon());
				app.put("width", rs.getWidth());
				app.put("height", rs.getHeight());
				app.put("url", rs.getUrl());
				if(rs.getType().equals("window")){
					app.put("isresize", rs.getIsresize());
					app.put("isopenmax", rs.getIsopenmax());
					app.put("issetbar", rs.getIssetbar());
					app.put("isflash", rs.getIsflash());
				}					
			}else{
				app.put("error", "ERROR_NOT_FOUND");
			}
		 }
		 return JSONObject.toJSONString(app);
		}
	
		 
	 
	 /**
	  * 安装应用
	  * @param data
	  * @throws ClassNotFoundException
	  * @throws NoSuchMethodException
	  * @throws SecurityException
	  * @throws IllegalAccessException
	  * @throws IllegalArgumentException
	  * @throws InvocationTargetException void
	  * koumiba
	  * 2017年3月28日
	  */
	private String addApp(Map<String, String> data) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		String type = data.get("type");
		
		int nextMemberAppTbid = 0;//下条插入的MemberApp数据id
		// 获取最新插入的一条数据id
		EntityWrapper ew = new EntityWrapper<MemberApp>(new MemberApp());
		ew.orderBy("tbid", false);
		MemberApp maTemp = memberAppService.selectOne(ew);
		nextMemberAppTbid = maTemp == null ?  1 : maTemp.getTbid().intValue()+1;
		
		if("file".equals(type)){
			MemberApp newMa = new MemberApp();
			newMa.setTbid((long)nextMemberAppTbid);
			newMa.setIcon(data.get("icon"));
			newMa.setName(data.get("name"));
			newMa.setUrl(data.get("url"));
			newMa.setExt(data.get("ext"));
			newMa.setSize(Integer.parseInt(data.get("size")));
			newMa.setWidth(600);
			newMa.setHeight(400);
			newMa.setType(data.get("type"));
			newMa.setDt(new Date());
			newMa.setLastdt(new Date());
			newMa.setMemberId((long)HoorayosHelper.getMemberId(request));
			memberAppService.insertOrUpdate(newMa);
			
		}else if("folder".equals(type)){
			MemberApp newMa = new MemberApp();
			newMa.setTbid((long)nextMemberAppTbid);
			newMa.setIcon(data.get("icon"));
			newMa.setName(data.get("name"));
			newMa.setWidth(600);
			newMa.setHeight(400);
			newMa.setType(data.get("type"));
			newMa.setDt(new Date());
			newMa.setLastdt(new Date());
			newMa.setMemberId((long)HoorayosHelper.getMemberId(request));
			memberAppService.insertOrUpdate(newMa);
			
		}else if ("pwindow".equals(type) || "pwidget".equals(type)){
			MemberApp newMa = new MemberApp();
			newMa.setTbid((long)nextMemberAppTbid);
			newMa.setIcon(data.get("icon"));
			newMa.setName(data.get("name"));
			newMa.setUrl(data.get("url"));
			newMa.setExt(data.get("ext"));
			newMa.setSize(Integer.parseInt(data.get("size")));
			newMa.setWidth(Integer.parseInt(data.get("width")));
			newMa.setHeight(Integer.parseInt(data.get("height")));
			newMa.setType(data.get("type"));
			newMa.setIsresize(Integer.parseInt(data.get("isresize")));
			newMa.setIsopenmax(Integer.parseInt(data.get("isopenmax")));
			newMa.setIsflash(Integer.parseInt(data.get("isflash")));
			newMa.setDt(new Date());
			newMa.setLastdt(new Date());
			newMa.setMemberId((long)HoorayosHelper.getMemberId(request));
			memberAppService.insertOrUpdate(newMa);
		}else{
			//检查应用是否已安装
			ew = new EntityWrapper(new MemberApp());
			ew.and("realid="+data.get("id") + " AND member_id="+HoorayosHelper.getMemberId(request));
			MemberApp ma = new MemberApp().selectOne(ew);
			if(ma == null){
				//查找应用信息
				ew = new EntityWrapper(new App());
				ew.and("tbid="+data.get("id"));
				App app = appService.selectOne(ew);
				//在安装应用表里更新一条记录	
				ma = new MemberApp();
				ma.setTbid((long)nextMemberAppTbid);
				ma.setRealid(Long.parseLong(data.get("id")));
				ma.setIcon(app.getIcon());
				ma.setName(app.getName());
				ma.setWidth(app.getWidth());
				ma.setHeight(app.getHeight());
				ma.setType(app.getType());
				ma.setIsresize(app.getIsresize());
				ma.setIsopenmax(app.getIsopenmax());
				ma.setIsflash(app.getIsflash());
				ma.setIssetbar(app.getIssetbar());
				ma.setDt(new Date());
				ma.setLastdt(new Date());
				ma.setMemberId((long)HoorayosHelper.getMemberId(request));
				memberAppService.insertOrUpdate(ma);
				
				//更新使用人数
				app.setUsecount(app.getUsecount()+1);
				appService.insertOrUpdate(app);				
			}
		}				
		
		if(nextMemberAppTbid>0 && Integer.parseInt(data.get("desk")) >= 1 && Integer.parseInt(data.get("desk")) <= 5){
			//将安装应用表返回的id记录到用户表
			int mid = HoorayosHelper.getMemberId(request);
			
			ew = new EntityWrapper<Member>(new Member());
			ew.and("tbid="+mid);
			Member mTemp = new Member().selectOne(ew);
			String deskTemp = data.get("desk");
			
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + deskTemp);
			String rs = (String) m.invoke(mTemp);
			
			m = c.getMethod("setDesk" + deskTemp, String.class);
			rs = (rs==null||rs.equals("")) ? nextMemberAppTbid+"" : rs+","+nextMemberAppTbid;
			m.invoke(mTemp, rs);
			memberService.insertOrUpdate(mTemp);
		}
		return "";
	}
	/**
	 * 删除应用
	 * @param id void
	 * koumiba
	 * 2017年4月4日
	 * @throws Exception 
	 */
	private void delApp(String id) throws Exception{
		int mid = HoorayosHelper.getMemberId(request);
		
		EntityWrapper ew = new EntityWrapper<MemberApp>();
		ew.setSqlSelect("realid,type,folder_id");
		ew.where("tbid="+id+" AND member_id="+mid);
		MemberApp mapp = new MemberApp().selectOne(ew);
		
		//如果是文件夹，则先删除文件夹内的应用
		if(mapp.getType().equals("folder")){
			ew = new EntityWrapper<MemberApp>();
			ew.and("folder_id="+id);
			List<MemberApp> appsInFloder = new MemberApp().selectList(ew);
			for(MemberApp ma : appsInFloder){
				delApp(ma.getTbid().toString());			
			}
		}else if("window".equals(mapp.getType()) || "widget".equals(mapp.getType())){//如果是系统应用，则更新应用的安装人数
			App app = appService.selectById(mapp.getRealid());
			app.setUsecount(app.getUsecount() - 1);;
			appService.insertOrUpdate(app);
		}
		
		//查询用户应用码头以及5个桌面的数据
		Member member = memberService.selectById(mid);
		
		if(!member.getDock().equals("")){
			String[] dockApp = member.getDock().split(",");
			List newDockApp = new ArrayList();
			for(String appid : dockApp){
				if(!id.equals(appid)){
					newDockApp.add(appid);
				}
			}
			member.setDock(org.apache.commons.lang.StringUtils.join(newDockApp.toArray(),","));
		}

		for(int i=1; i<=5; i++){
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + i);
			String rs = (String) m.invoke(member);
			if(rs == null) continue;
			String[] deskApp = rs.split(",");
			List newDeskApp = new ArrayList();
			for(String appid : deskApp){
				if(!id.equals(appid)){
					newDeskApp.add(appid);
				}
			}
			if(newDeskApp.size() > 0){
				Method setDesk = c.getMethod("setDesk"+i, String.class);
				setDesk.invoke(member, org.apache.commons.lang.StringUtils.join(newDeskApp.toArray(),","));
			}
		}
		
		memberService.insertOrUpdate(member);
		
		new MemberApp().delete(ew);
	}

	/**
	 * 移动桌面图标
	 * @param parameterMap void
	 * koumiba
	 * 2017年4月4日
	 * @throws Exception 
	 * @throws NoSuchMethodException 
	 */
	private void moveApp() throws NoSuchMethodException, Exception {
		/*
		 * 传入参数
		 */
		String moveType = request.getParameter("movetype"); 
		String id = request.getParameter("id"); 
		String boa = request.getParameter("boa"); 
		int to = request.getParameter("to")==null ? 0 : Integer.parseInt(request.getParameter("to")); 
		int from = request.getParameter("from")==null ? 0 : Integer.parseInt(request.getParameter("from")); 
		int desk = request.getParameter("desk")==null ? 0: Integer.parseInt(request.getParameter("desk")); 
		int toDesk = request.getParameter("todesk")==null ? 0 : Integer.parseInt(request.getParameter("todesk")); 
		int fromDesk = request.getParameter("fromdesk")==null ? 0 : Integer.parseInt(request.getParameter("fromdesk")); 
		
		int mid = HoorayosHelper.getMemberId(request);
		Member member = memberService.selectById(mid);
		EntityWrapper ewMa = new EntityWrapper<MemberApp>();
		
		if(moveType.equals("dock-folder")){
			member.setDock(HoorayosHelper.removeItem(member.getDock().split(","), id));
			memberService.insertOrUpdate(member);
			
			ewMa.where("member_id="+mid+" AND tbid="+id).setSqlSelect("folder_id");
			MemberApp ma = new MemberApp().selectOne(ewMa);
			ma.setFolderId((long)to);
			memberAppService.insertOrUpdate(ma);
			
		}else if(moveType.equals("dock-dock")){
				String[] dockArr = member.getDock().split(",");
				String newDock = "";
				//判断传入的应用id和数据库里的id是否吻合
				if(dockArr[from].equals(id)){
					if(to == 0){
						if(boa!=null && boa.equals("b")){
							 newDock = HoorayosHelper.insertItem(dockArr, 0, id);
						}else{
							 newDock = HoorayosHelper.insertItem(dockArr, 1, id);							
						}						
					}else{
						if(boa!=null && boa.equals("b")){
							 newDock = HoorayosHelper.insertItem(dockArr, to, id);
						}else{
							 newDock = HoorayosHelper.insertItem(dockArr, to+1, id);							
						}		
					}
					dockArr = newDock.split(",");
					if(from >to){
						newDock = HoorayosHelper.removeItem(dockArr, from+1);
					}else{
						newDock = HoorayosHelper.removeItem(dockArr, from);
					}
					member.setDock(newDock);
					memberService.insertOrUpdate(member);
				}
		}else if(moveType.equals("dock-desk")){
			String newDock = "", newDesk = "";
			String[] dockArr =  member.getDock().split(",");
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + desk);
			String rs = (String) m.invoke(member);
			String[] deskArr = (rs==null ? new String[]{""} : rs.split(","));
			
			newDock = HoorayosHelper.removeItem(dockArr, from);
			
			if(deskArr[0].equals("")){
				newDesk = id;
			}else{
				if(to == 0){
					if(boa!=null && boa.equals("b")){
						newDesk = HoorayosHelper.insertItem(deskArr, 0, id);
					}else{
						newDesk = HoorayosHelper.insertItem(deskArr, 1, id);							
					}										
				}else{
					if(boa!=null && boa.equals("b")){
						newDesk = HoorayosHelper.insertItem(deskArr, to, id);
					}else{
						newDesk = HoorayosHelper.insertItem(deskArr, to+1, id);							
					}	
				}
			}
			member.setDock(newDock);
			Method setDesk = c.getMethod("setDesk"+desk, String.class);
			setDesk.invoke(member, newDesk);
			memberService.insertOrUpdate(member);
		}else if(moveType.equals("dock-otherdesk")){
			String newDock = "";
			String[] dockArr =  member.getDock().split(",");
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + toDesk);
			String rs = (String) m.invoke(member);
			String[] deskArr = (rs==null ? new String[]{""} : rs.split(","));
			
			
			newDock = HoorayosHelper.removeItem(dockArr, from);
			if(deskArr[0].equals("")){
				deskArr[0] = id;
			}else{
				String[] deskTempArr = new String[deskArr.length+1];
				deskTempArr = Arrays.copyOf(deskArr, deskArr.length);
				deskTempArr[deskArr.length+1] = id;
				deskArr = deskTempArr;
			}
			member.setDock(newDock);
			Method setDesk = c.getMethod("setDesk"+toDesk, String.class);
			setDesk.invoke(member, org.apache.commons.lang.StringUtils.join(deskArr,","));
			memberService.insertOrUpdate(member);
		}else if(moveType.equals("desk-folder")){
			String newDesk = "";
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + desk);
			String rs = (String) m.invoke(member);
			String[] deskArr = (rs==null ? new String[]{""} : rs.split(","));
			
			newDesk = HoorayosHelper.removeItem(deskArr, id);
			Method setDesk = c.getMethod("setDesk"+desk, String.class);
			setDesk.invoke(member, newDesk);
			
			ewMa.where("member_id="+mid+" AND tbid="+id).setSqlSelect("folder_id");
			MemberApp ma = new MemberApp().selectOne(ewMa);
			ma.setFolderId((long)to);
			memberAppService.insertOrUpdate(ma);
		}else if(moveType.equals("desk-dock")){
			String newDock = "", newDesk = "";
			String temp = member.getDock() == null ? "" : member.getDock();
			String[] dockArr = temp.split(",");
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + desk);
			String rs = (String) m.invoke(member);
			String[] deskArr = (rs==null ? new String[]{""} : rs.split(","));
			
			newDesk = HoorayosHelper.removeItem(deskArr, from);
			
			if(dockArr[0].equals("")){
				newDock = id;
			}else{
				if(to == 0){
					if(boa!=null && boa.equals("b")){
						 newDock = HoorayosHelper.insertItem(dockArr, 0, id);
					}else{
						 newDock = HoorayosHelper.insertItem(dockArr, 1, id);							
					}						
				}else{
					if(boa!=null && boa.equals("b")){
						 newDock = HoorayosHelper.insertItem(dockArr, to, id);
					}else{
						 newDock = HoorayosHelper.insertItem(dockArr, to+1, id);							
					}		
				}			
			}
			dockArr = newDock.split(",");
			if(dockArr.length > 7){
				HoorayosHelper.insertItem(deskArr, -1, dockArr[7]);
				newDock = HoorayosHelper.removeItem(dockArr, 7);
			}
			member.setDock(newDock);
			Method setDesk = c.getMethod("setDesk"+desk, String.class);
			setDesk.invoke(member, newDesk);
			memberService.insertOrUpdate(member);
		}else if(moveType.equals("desk-desk")){
			String[] dockArr = member.getDock().split(",");
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method m = c.getMethod("getDesk" + desk);
			String rs = (String) m.invoke(member);
			String[] deskArr = (rs==null ? new String[]{""} : rs.split(","));
			String newDesk = "";
			//判断传入的应用id和数据库里的id是否吻合
			if(deskArr[from].equals(id)){
				if(to == 0){
					if(boa!=null && boa.equals("b")){
						newDesk = HoorayosHelper.insertItem(deskArr, 0, id);
					}else{
						newDesk = HoorayosHelper.insertItem(deskArr, 1, id);							
					}						
				}else{
					if(boa!=null && boa.equals("b")){
						newDesk = HoorayosHelper.insertItem(deskArr, to, id);
					}else{
						newDesk = HoorayosHelper.insertItem(deskArr, to+1, id);							
					}		
				}
				deskArr = newDesk.split(",");
				if(from >to){
					newDesk = HoorayosHelper.removeItem(deskArr, from+1);
				}else{
					newDesk = HoorayosHelper.removeItem(deskArr, from);
				}
				Method setDesk = c.getMethod("setDesk"+desk, String.class);
				setDesk.invoke(member, newDesk);
				memberService.insertOrUpdate(member);
			}
		}else if(moveType.equals("desk-otherdesk")){
			String newToDesk = "";
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method mfromDesk = c.getMethod("getDesk" + fromDesk);
			Method mtoDesk = c.getMethod("getDesk" + toDesk);
			String rs = (String) mfromDesk.invoke(member);
			String[] fromDeskArr = (rs==null ? new String[]{""} : rs.split(","));
			rs = (String) mtoDesk.invoke(member);
			String[] toDeskArr = (rs==null ? new String[]{""} : rs.split(","));
			
			String temp = HoorayosHelper.removeItem(fromDeskArr, from);
			fromDeskArr = temp.split(",");
			if(toDeskArr[0].equals("")){
				newToDesk = id;
			}else{
				if(to == 0){
					if(boa!=null && boa.equals("b")){
						newToDesk = HoorayosHelper.insertItem(toDeskArr, 0, id);
					}else{
						newToDesk = HoorayosHelper.insertItem(toDeskArr, 1, id);							
					}						
				}else{
					if(boa!=null && boa.equals("b")){
						newToDesk = HoorayosHelper.insertItem(toDeskArr, to, id);
					}else{
						newToDesk = HoorayosHelper.insertItem(toDeskArr, to+1, id);							
					}		
				}
			}
			Method setFromDesk = c.getMethod("setDesk"+fromDesk, String.class);
			Method setToDesk = c.getMethod("setDesk"+toDesk, String.class);
			setFromDesk.invoke(member, org.apache.commons.lang.StringUtils.join(fromDeskArr,","));
			setToDesk.invoke(member, newToDesk);
			memberService.insertOrUpdate(member);
		}else if(moveType.equals("folder-folder")){
			ewMa.where("member_id="+mid+" AND tbid="+id).setSqlSelect("folder_id");
			MemberApp ma = new MemberApp().selectOne(ewMa);
			ma.setFolderId((long)to);
			memberAppService.insertOrUpdate(ma);
		}
		/*else if(moveType.equals("folder-dock")){
			$rs = $db->get('tb_member', array('dock', 'desk'.$_POST['desk']), array(
					'tbid' => session('member_id')
				));
				$dock_arr = explode(',', $rs['dock']);
				$desk_arr = explode(',', $rs['desk'.$_POST['desk']]);
				if($dock_arr[0] == ''){
					$dock_arr[0] = $_POST['id'];
				}else{
					if($_POST['to'] == 0){
						if($_POST['boa'] == 'b'){
							array_splice($dock_arr, 0, 0, $_POST['id']);
						}else{
							array_splice($dock_arr, 1, 0, $_POST['id']);
						}
					}else{
						if($_POST['boa'] == 'b'){
							array_splice($dock_arr, $_POST['to'], 0, $_POST['id']);
						}else{
							array_splice($dock_arr, $_POST['to'] + 1, 0, $_POST['id']);
						}
					}
				}
				if(count($dock_arr) > 7){
					$desk_arr[] = $dock_arr[7];
					unset($dock_arr[7]);
				}
				$db->update('tb_member', array(
					'dock' => implode(',', $dock_arr),
					'desk'.$_POST['desk'] => implode(',', $desk_arr)
				), array(
					'tbid' => session('member_id')
				));
				$db->update('tb_member_app', array(
					'folder_id' => 0
				), array(
					'AND' => array(
						'tbid' => $_POST['id'],
						'member_id' => session('member_id')
					)
				));
				break;
		}else if(moveType.equals("folder-desk")){
			
			$desk = $db->get('tb_member', 'desk'.$_POST['desk'], array(
					'tbid' => session('member_id')
				));
				$desk_arr = explode(',', $desk);
				if($desk_arr[0] == ''){
					$desk_arr[0] = $_POST['id'];
				}else{
					if($_POST['to'] == 0){
						if($_POST['boa'] == 'b'){
							array_splice($desk_arr, 0, 0, $_POST['id']);
						}else{
							array_splice($desk_arr, 1, 0, $_POST['id']);
						}
					}else{
						if($_POST['boa'] == 'b'){
							array_splice($desk_arr, $_POST['to'], 0, $_POST['id']);
						}else{
							array_splice($desk_arr, $_POST['to'] + 1, 0, $_POST['id']);
						}
					}
				}
				$db->update('tb_member', array(
					'desk'.$_POST['desk'] => implode(',', $desk_arr)
				), array(
					'tbid' => session('member_id')
				));
				$db->update('tb_member_app', array(
					'folder_id' => 0
				), array(
					'AND' => array(
						'tbid' => $_POST['id'],
						'member_id' => session('member_id')
					)
				));
				break;
		}else if(moveType.equals("folder-otherdesk")){
		
			$todesk = $db->get('tb_member', 'desk'.$_POST['todesk'], array(
					'tbid' => session('member_id')
				));
				$todesk_arr = explode(',', $todesk);
				if($todesk_arr[0] == ''){
					$todesk_arr[0] = $_POST['id'];
				}else{
					$todesk_arr[] = $_POST['id'];
				}
				$db->update('tb_member', array(
					'desk'.$_POST['todesk'] => implode(',', $todesk_arr)
				), array(
					'tbid' => session('member_id')
				));
				$db->update('tb_member_app', array(
					'folder_id' => 0
				), array(
					'AND' => array(
						'tbid' => $_POST['id'],
						'member_id' => session('member_id')
					)
				));
				break;
		}*/
			
	}
	/**
	 * 获取桌面背景
	 * @return String
	 * koumiba
	 * 2017年4月4日
	 */
	private String getWallpaper() {
		ArrayList<Object> wallpaperArr = new ArrayList<Object>();
		if(HoorayosHelper.checkLogin(request)){
			Member member = memberService.selectById(HoorayosHelper.getMemberId(request));
			
			if(member.getWallpaperstate()== 1){
				Wallpaper wp = wallpaperService.selectById(member.getWallpaperId());
				wallpaperArr.add(member.getWallpaperstate());	
				wallpaperArr.add(wp.getUrl());
				wallpaperArr.add(member.getWallpapertype());
				wallpaperArr.add(wp.getWidth());
				wallpaperArr.add(wp.getHeight());					
			}else if(member.getWallpaperstate() == 2){
				Pwallpaper pwp = pwallpaperService.selectById(member.getWallpaperId());
				wallpaperArr.add(member.getWallpaperstate());	
				wallpaperArr.add(pwp.getUrl());
				wallpaperArr.add(member.getWallpapertype());
				wallpaperArr.add(pwp.getWidth());
				wallpaperArr.add(pwp.getHeight());						
						
			}else if(member.getWallpaperstate()==3){
				wallpaperArr.add(member.getWallpaperstate());
				wallpaperArr.add(member.getWallpaperwebsite());
			}
		}else{
			Setting setting = settingService.selectById(1);
			Wallpaper wallpaper = wallpaperService.selectById(setting.getWallpaperId());
			wallpaperArr.add(1);
			wallpaperArr.add(wallpaper.getUrl());
			wallpaperArr.add(setting.getWallpapertype());
			wallpaperArr.add(wallpaper.getWidth());
			wallpaperArr.add(wallpaper.getHeight());
		}
		return org.apache.commons.lang.StringUtils.join(wallpaperArr.toArray(),"<{|}>");
	}
	/**
	 * 设置桌面背景 
	 *  void
	 * koumiba
	 * 2017年4月4日
	 */
	private void setWallpaper() {
		Member member = memberService.selectById(HoorayosHelper.getMemberId(request));
		String wpstate = request.getParameter("wpstate");
		String wptype = request.getParameter("wptype");
		String wp = request.getParameter("wp");
		if(wpstate.equals("0")){
			member.setWallpapertype(wptype);
		}else if(wpstate.equals("1")||wpstate.equals("2")){
			if(!wp.equals("") && wp != "0"){
				member.setWallpaperId(Integer.parseInt(wp));
			}
		}else if(wpstate.equals("3")){
			if(wp!=null && !wp.equals("")){
				member.setWallpaperwebsite(wp);
			}
		}
		member.setWallpaperstate(Integer.parseInt(wpstate));
		member.setWallpapertype(wptype);
		memberService.insertOrUpdate(member);
	}
	

	/**
	 * 更新应用码头
	 * @return String
	 * koumiba
	 * 2017年4月11日
	 * @throws Exception 
	 */
	private void setDockPos() throws Exception {
		int mid = HoorayosHelper.getMemberId(request);
		Member member = memberService.selectById(mid);
		String dock = request.getParameter("dock");
		String desk = request.getParameter("desk");
		member.setDockpos(dock);
		memberService.insertOrUpdate(member);
		
		if(dock.equals("none")){
			Member rs = memberService.selectById(mid);
			String dockArr = rs.getDock();
			Class<?> c = Class
					.forName("com.baomidou.springwind.entity.Member");
			Method deskMethod = c.getMethod("getDesk" + desk);
			String deskArr = (String) deskMethod.invoke(member);
			if(dockArr != null && !dockArr.equals("")){
				if(deskArr.equals("")){
					deskArr = dockArr;
				}else{
					deskArr = deskArr+","+dockArr;
				}
				member.setDock("");
				
				Method setDeskMethod = c.getMethod("setDesk"+desk, String.class);
				setDeskMethod.invoke(member, deskArr);
				
			}
		}
	}
}
